<?php

namespace app\hook;

use Illuminate\Database\Capsule\Manager as DB;

class userregister
{
    public function successed($params = [])
    {
        $member = $params['member'];
        $inviter = $params['inviter'];

        // 邀请人奖励
        $reward_score = DB::table('sys_config')
            ->where('type', 18)
            ->where('key', 'recommend_score')
            ->value('value') ?: 0;
        if ($reward_score) {
            \memberModel::score($reward_score, $inviter, 'share', 0, '邀请用户获得积分 受邀用户id:' . $member->id);
        }

        // 记录团队关系邀请人邀请人
        $to_insert = [['member_id' => $inviter->id, 'level' => 1, 'children_id' => $member->id]];
        \memberchildrenModel::where('children_id', $inviter->id)
            ->select(['member_id', 'level', 'member_id'])
            ->orderBy('level')
            ->chunk(500, function($items) use ($member, &$to_insert) {
                foreach ($items as $item) {
                    $to_insert[] = [
                        'member_id' => $item->member_id,
                        'level' => $item['level'] + 1,
                        'children_id' => $member->id,
                    ];
                }
                \memberchildrenModel::insertOrIgnore($to_insert);
                $to_insert = [];
            });
        if (!empty($to_insert)) {
            \memberchildrenModel::insertOrIgnore($to_insert);
        }

        \Log::out('用户注册成功，记录团队关系，奖励邀请人', 'hook');
    }
}

